package com.ms.controller;

import com.ms.entity.Score;
import com.ms.entity.Schedule;
import com.ms.entity.Registration;
import com.ms.entity.User;
import com.ms.service.inter.ScoreService;
import com.ms.service.inter.ScheduleService;
import com.ms.dao.RegistrationMapper;
import com.ms.utils.SimpleTokenUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.math.BigDecimal;

/**
 * 成绩控制器 - 处理成绩相关的HTTP请求
 */
@RestController
@RequestMapping("/score")
public class ScoreController {

    @Autowired
    private ScoreService scoreService;
    
    @Autowired
    private ScheduleService scheduleService;
    
    @Autowired
    private RegistrationMapper registrationMapper;

    /**
     * 添加成绩接口
     * @param score 成绩对象
     * @return 添加结果
     */
    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> addScore(@RequestBody Score score, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (userObj == null) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            // 设置默认轮次为1
            if (score.getRankId() == null) {
                score.setRankId(1);
            }
            
            // 根据gameId、eventId和rankId获取赛程ID
            Schedule schedule = scheduleService.getOne(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Schedule>()
                    .eq("gameID", score.getGameId())
                    .eq("eventID", score.getEventId())
                    .eq("`rank`", score.getRankId())
            );
            
            if (schedule == null) {
                result.put("success", false);
                result.put("message", "未找到对应的赛程信息");
                return ResponseEntity.badRequest().body(result);
            }
            
            score.setScheId(schedule.getSchId());
            
            // 检查是否已存在相同记录（同一用户在同一比赛项目同一轮次只能有一条记录）
            Score existingScore = scoreService.getOne(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Score>()
                    .eq("user_id", score.getUserId())
                    .eq("game_id", score.getGameId())
                    .eq("event_id", score.getEventId())
                    .eq("rank_id", score.getRankId())
            );
            
            if (existingScore != null) {
                result.put("success", false);
                result.put("message", "该用户在此项目此轮次已存在成绩记录");
                return ResponseEntity.badRequest().body(result);
            }

            // 保存成绩信息
            scoreService.save(score);

            result.put("success", true);
            result.put("message", "成绩添加成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "成绩添加失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 批量添加成绩接口
     * @param gameId 比赛ID
     * @param eventId 项目ID
     * @param request HTTP请求
     * @return 添加结果
     */
    @PostMapping("/batchAdd")
    public ResponseEntity<Map<String, Object>> batchAddScores(@RequestParam Integer gameId, 
                                                              @RequestParam Integer eventId,
                                                              HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (userObj == null) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            // 设置默认轮次为1
            Integer rankId = 1;
            
            // 根据gameId、eventId和rankId获取赛程ID
            Schedule schedule = scheduleService.getOne(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Schedule>()
                    .eq("gameID", gameId)
                    .eq("eventID", eventId)
                    .eq("`rank`", rankId)
            );
            
            if (schedule == null) {
                result.put("success", false);
                result.put("message", "未找到对应的赛程信息，gameId:" + gameId + ", eventId:" + eventId + ", rankId:" + rankId);
                return ResponseEntity.badRequest().body(result);
            }

            // 获取比赛项目的所有报名且通过审核的用户信息
            List<Registration> registrations = registrationMapper.selectList(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Registration>()
                    .eq("gameID", gameId)
                    .eq("eventID", eventId)
                    .eq("isUsing", 1)
            );
            
            if (registrations == null || registrations.isEmpty()) {
                result.put("success", false);
                result.put("message", "未找到已报名并通过审核的用户");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 获取用户信息并构造成绩记录
            List<Score> scores = new ArrayList<>();
            int skippedCount = 0; // 记录跳过的用户数量
            for (Registration registration : registrations) {
                User user = registrationMapper.selectUserById(registration.getUserID());
                if (user != null) {
                    // 检查是否已存在相同记录（同一用户在同一比赛项目同一轮次只能有一条记录）
                    Score existingScore = scoreService.getOne(
                        new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Score>()
                            .eq("user_id", user.getUserID())
                            .eq("game_id", gameId)
                            .eq("event_id", eventId)
                            .eq("rank_id", rankId)
                    );
                    
                    // 如果已存在记录，则跳过该用户，不返回错误
                    if (existingScore != null) {
                        skippedCount++;
                        continue;
                    }
                    
                    Score score = new Score();
                    score.setUserId(user.getUserID());
                    score.setUserName(user.getUsername());
                    score.setGameId(gameId);
                    score.setEventId(eventId);
                    score.setScheId(schedule.getSchId());
                    score.setRankId(rankId);
                    scores.add(score);
                }
            }

            // 如果没有需要添加的记录
            if (scores.isEmpty()) {
                result.put("success", true);
                result.put("message", "没有需要添加的成绩记录，所有用户的成绩已存在或无有效用户");
                return ResponseEntity.ok(result);
            }

            // 批量保存成绩信息
            boolean saveResult = scoreService.saveBatch(scores);

            result.put("success", true);
            result.put("message", "成绩批量添加成功，共添加 " + scores.size() + " 条记录，跳过 " + skippedCount + " 条已存在的记录");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "成绩批量添加失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据ID获取成绩信息接口
     * @param sId 成绩ID
     * @param request HTTP请求
     * @return 成绩信息
     */
    @GetMapping("/info")
    public ResponseEntity<Map<String, Object>> getScoreInfo(@RequestParam Integer sId, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (userObj == null) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            Score score = scoreService.findById(sId);
            if (score == null) {
                result.put("success", false);
                result.put("message", "成绩不存在");
                return ResponseEntity.badRequest().body(result);
            }

            result.put("success", true);
            result.put("score", score);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取成绩信息失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 更新成绩信息接口
     * @param sId 成绩ID
     * @param scoreData 更新的成绩数据
     * @param request HTTP请求
     * @return 更新结果
     */
    @PutMapping("/update")
    public ResponseEntity<Map<String, Object>> updateScore(@RequestParam Integer sId, @RequestBody Score scoreData, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (userObj == null) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            Score existingScore = scoreService.findById(sId);
            if (existingScore == null) {
                result.put("success", false);
                result.put("message", "成绩不存在");
                return ResponseEntity.badRequest().body(result);
            }

            // 更新字段
            if (scoreData.getUserId() != null) {
                existingScore.setUserId(scoreData.getUserId());
            }
            if (scoreData.getUserName() != null) {
                existingScore.setUserName(scoreData.getUserName());
            }
            if (scoreData.getGameId() != null) {
                existingScore.setGameId(scoreData.getGameId());
            }
            if (scoreData.getEventId() != null) {
                existingScore.setEventId(scoreData.getEventId());
            }
            if (scoreData.getScheId() != null) {
                existingScore.setScheId(scoreData.getScheId());
            }
            if (scoreData.getRankId() != null) {
                existingScore.setRankId(scoreData.getRankId());
            }
            if (scoreData.getIsPromoted() != null) {
                existingScore.setIsPromoted(scoreData.getIsPromoted());
            }
            if (scoreData.getSDistance() != null) {
                existingScore.setSDistance(scoreData.getSDistance());
            }
            if (scoreData.getSScore() != null) {
                existingScore.setSScore(scoreData.getSScore());
            }
            if (scoreData.getSTimeValue() != null) {
                existingScore.setSTimeValue(scoreData.getSTimeValue());
            }
            if (scoreData.getSType() != null) {
                existingScore.setSType(scoreData.getSType());
            }

            scoreService.update(existingScore);

            result.put("success", true);
            result.put("message", "成绩信息更新成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新成绩信息失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 删除成绩接口
     * @param sId 成绩ID
     * @param request HTTP请求
     * @return 删除结果
     */
    @DeleteMapping("/delete")
    public ResponseEntity<Map<String, Object>> deleteScore(@RequestParam Integer sId, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (userObj == null) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            Score existingScore = scoreService.findById(sId);
            if (existingScore == null) {
                result.put("success", false);
                result.put("message", "成绩不存在");
                return ResponseEntity.badRequest().body(result);
            }

            scoreService.delete(sId);

            result.put("success", true);
            result.put("message", "成绩删除成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除成绩失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取所有成绩接口
     * @param request HTTP请求
     * @return 所有成绩列表
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getAllScores(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (userObj == null) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            List<Score> scores = scoreService.list();

            result.put("success", true);
            result.put("scores", scores);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取成绩列表失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
    
    /**
     * 根据eventId和轮次查询成绩数据，并根据s_type排序
     * @param eventId 项目ID
     * @param rankId 轮次
     * @param request HTTP请求
     * @return 成绩列表
     */
    @GetMapping("/listByEventAndRank")
    public ResponseEntity<Map<String, Object>> getScoresByEventIdAndRankIdWithOrder(
            @RequestParam Integer eventId,
            @RequestParam Integer rankId,
            HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (userObj == null) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            List<Score> scores = scoreService.findByEventIdAndRankIdWithOrder(eventId, rankId);

            result.put("success", true);
            result.put("scores", scores);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取成绩列表失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 成绩晋级操作接口
     * 将指定成绩的isPromoted改为1，并增加一条下一轮的成绩数据
     * @param sId 成绩ID
     * @param request HTTP请求
     * @return 晋级结果
     */
    @PostMapping("/promote")
    public ResponseEntity<Map<String, Object>> promoteScore(@RequestParam Integer sId, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (userObj == null) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            // 查找当前成绩记录
            Score existingScore = scoreService.findById(sId);
            if (existingScore == null) {
                result.put("success", false);
                result.put("message", "成绩不存在");
                return ResponseEntity.badRequest().body(result);
            }

            // 更新当前成绩为已晋级
            existingScore.setIsPromoted(1);
            scoreService.update(existingScore);

            // 创建下一轮成绩记录
            Score nextRoundScore = new Score();
            nextRoundScore.setUserId(existingScore.getUserId());
            nextRoundScore.setUserName(existingScore.getUserName());
            nextRoundScore.setGameId(existingScore.getGameId());
            nextRoundScore.setEventId(existingScore.getEventId());
            nextRoundScore.setRankId(existingScore.getRankId() + 1); // 轮次加1

            // 根据gameId、eventId和新的rankId获取赛程ID
            Schedule schedule = scheduleService.getOne(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Schedule>()
                    .eq("gameID", nextRoundScore.getGameId())
                    .eq("eventID", nextRoundScore.getEventId())
                    .eq("`rank`", nextRoundScore.getRankId())
            );

            if (schedule == null) {
                result.put("success", false);
                result.put("message", "未找到下一轮对应的赛程信息");
                return ResponseEntity.badRequest().body(result);
            }

            nextRoundScore.setScheId(schedule.getSchId());

            // 保存下一轮成绩记录
            scoreService.save(nextRoundScore);

            result.put("success", true);
            result.put("message", "成绩晋级成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "成绩晋级失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 批量更新成绩接口
     * @param scores 成绩列表，每个对象需包含sId、SScore和SType属性
     * @param request HTTP请求
     * @return 更新结果
     */
    @PutMapping("/saveScores")
    public ResponseEntity<Map<String, Object>> batchUpdateScores(@RequestBody List<Score> scores, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        System.out.println("调用了这个方法调用了这个方法调用了这个方法调用了这个方法调用了这个方法调用了这个方法");
        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (userObj == null) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            // 检查传入数据是否为空
            if (scores == null || scores.isEmpty()) {
                result.put("success", false);
                result.put("message", "成绩列表不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            // 过滤出有效的成绩记录（必须包含sId、SScore和SType）
            List<Score> validScores = new ArrayList<>();
            for (Score score : scores) {
                if (score.getSId() != null && (score.getSScore() != null || score.getSType() != null)) {
                    validScores.add(score);
                }
            }

            if (validScores.isEmpty()) {
                result.put("success", false);
                result.put("message", "没有有效的成绩记录需要更新");
                return ResponseEntity.badRequest().body(result);
            }

            // 批量更新成绩
            int updatedCount = 0;
            for (Score score : validScores) {
                Score existingScore = scoreService.findById(score.getSId());
                if (existingScore != null) {
                    // 根据sType的值更新对应的成绩字段
                    if (score.getSType() != null) {
                        existingScore.setSType(score.getSType());
                        
                        // 根据类型更新对应的成绩字段
                        switch (score.getSType()) {
                            case 1: // 更新距离成绩
                                if (score.getSDistance() != null) {
                                    existingScore.setSDistance(score.getSDistance());
                                }
                                break;
                            case 2: // 更新得分成绩
                                if (score.getSScore() != null) {
                                    existingScore.setSScore(score.getSScore());
                                }
                                break;
                            case 3: // 更新时间成绩
                                if (score.getSTimeValue() != null) {
                                    existingScore.setSTimeValue(score.getSTimeValue());
                                }
                                break;
                            default:
                                // 其他情况不更新具体成绩字段
                                break;
                        }
                    } else {
                        // 如果没有指定类型，按照原来的方式更新字段
                        if (score.getSScore() != null) {
                            existingScore.setSScore(score.getSScore());
                        }
                        if (score.getSType() != null) {
                            existingScore.setSType(score.getSType());
                        }
                    }

                    scoreService.update(existingScore);
                    updatedCount++;
                }
            }

            result.put("success", true);
            result.put("message", "成绩批量更新成功，共更新 " + updatedCount + " 条记录");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量更新成绩失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 取消成绩晋级操作接口
     * 将指定成绩的isPromoted改为0，并删除对应的下一轮成绩数据
     * @param sId 成绩ID
     * @param request HTTP请求
     * @return 取消晋级结果
     */
    @PostMapping("/cancelPromote")
    public ResponseEntity<Map<String, Object>> cancelPromoteScore(@RequestParam Integer sId, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (userObj == null) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            // 查找当前成绩记录
            Score existingScore = scoreService.findById(sId);
            if (existingScore == null) {
                result.put("success", false);
                result.put("message", "成绩不存在");
                return ResponseEntity.badRequest().body(result);
            }

            // 更新当前成绩为未晋级
            existingScore.setIsPromoted(0);
            scoreService.update(existingScore);

            // 删除下一轮成绩记录
            Score nextRoundScore = scoreService.getOne(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Score>()
                    .eq("user_id", existingScore.getUserId())
                    .eq("game_id", existingScore.getGameId())
                    .eq("event_id", existingScore.getEventId())
                    .eq("rank_id", existingScore.getRankId() + 1)
            );

            if (nextRoundScore != null) {
                scoreService.delete(nextRoundScore.getSId());
            }

            result.put("success", true);
            result.put("message", "取消晋级操作成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "取消晋级操作失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取当前用户的所有成绩
     * @param request HTTP请求
     * @return 成绩列表
     */
    @GetMapping("/myScores")
    public ResponseEntity<Map<String, Object>> getMyScores(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            Object userObj = SimpleTokenUtils.getUserByToken(token);
            if (!(userObj instanceof User)) {
                result.put("success", false);
                result.put("message", "无权限访问");
                return ResponseEntity.badRequest().body(result);
            }

            User currentUser = (User) userObj;
            
            // 根据用户ID查询成绩
            List<Score> scores = scoreService.list(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Score>()
                    .eq("user_id", currentUser.getUserID())
            );

            result.put("success", true);
            result.put("scores", scores);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取成绩列表失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    
}